#ifndef WU_THREAD_H
#define WU_THREAD_H
#include <mutex>
#include <condition_variable>
#include <thread>
#include <atomic>
#include <functional>
#include <memory>

struct Thread_notifyer
{
    std::function<void(int,int)> pstart;
    std::function<void(int,int)> pstop;
};

extern Thread_notifyer dumynotifer;

typedef std::shared_ptr<Thread_notifyer> ThreadNotifyer;
typedef std::function<void(std::shared_ptr<void> ptrArgs)> FuncType;

enum ThreadStatus
{
    THREAD_UNINIT,
    THREAD_INITING,
    THREAD_RUN,
    THREAD_STOPPING,
    THREAD_STOPPED
};


class ThreadInterface : public std::enable_shared_from_this<ThreadInterface>
{
    protected:
        const int           id_;
        std::atomic_int     runflag_;  
        ThreadNotifyer      notifyer_;    
    public:
        ThreadInterface(int id,ThreadNotifyer note);
        virtual ~ThreadInterface();
        virtual int Start() = 0;
        virtual int Stop() = 0;
        virtual int Post(FuncType func, std::shared_ptr<void> args) = 0;
};

class ThreadFactory
{
    private:
        ThreadFactory();
        static ThreadFactory* pins;
    public:
        ~ThreadFactory();
        static ThreadFactory* GetInstance();
        std::shared_ptr<ThreadInterface> CreatThread(int type,int id,ThreadNotifyer note);
};

class Thread : public ThreadInterface
{
private:
    std::unique_ptr<std::thread>    pointer2stdthread_;
    FuncType                        customfunction_;
    std::shared_ptr<void>           customargs_;
    std::mutex                      signalmutex_;
    std::condition_variable         signalcond_;

public:
    Thread(const int id,ThreadNotifyer pNotify);
    int Start();
    int Stop();
    int threadfunc();
    int Post(FuncType func, std::shared_ptr<void> args);
    virtual ~Thread();
};

#endif
